//下载一个vue-router
import{createRouter,createWebHashHistory} from 'vue-router'
//此处可以换为createwebhistory
import Login from '@/views/Login.vue'
import MainBox from '@/views/MainBox.vue'
import NotFound from '@/views/notfound/NotFound.vue'
import RouteConfig from './config'
import {useRouterStore} from '../store/useRouterStore'
import { useUserStore } from '../store/useUserStore'


const routes =[
    {
        path:"/login",
        name:"login",
        component:Login
    },
    {
        path:"/mainbox",
        name:"mainbox",
        component:MainBox
    }
]
const router = createRouter({
    //哈希表形式会以井号斜杠也就是//#/login出现
    history:createWebHashHistory(),
    routes:routes

})

//添加路由
// router.addRoute("mainbox",{
//     path:"/index",
//     component:Home

// })

//路由拦截：任何路由跳转的时候都会经过这个拦截
router.beforeEach((to,from,next)=>{
    const {isGetterRouter} = useRouterStore()
    const {user} = useUserStore()
    //next()
    if(to.name === "login"){
            next() 
    }
    else{
        if(!user.role){
            //跳转登录
            next({
                path:"/login"
            })
        }else{
            //必须记录第一次才调用，不然每次跳转都会遍历且配置一遍。
            if(!isGetterRouter){
            //删除主盒子
                router.removeRoute("mainbox")
                ConfigRouter()
                next({
                    //相当于在走一遍新配置好的同一个路径
                    path:to.fullPath
                })
            }else{
                next()
            }
            
        }
    }
       
})

const ConfigRouter = ()=>{
    //重新生成主盒子
    router.addRoute({
        path:"/mainbox",
        name:"mainbox",
        component:MainBox
    })
    let {changeRouter} = useRouterStore()
    RouteConfig.forEach(item=>{
        //遍历以全部添加为mainbox的孩子
        checkPermission(item.path) && router.addRoute("mainbox",item)
    })

    //重定向
    router.addRoute("mainbox",{
        path:"/",
        redirect:"/index"
    })
    //404
    router.addRoute("mainbox",{
        path:"/:pathMatch(.*)*",
        component:NotFound
    })
 
    //结束后刷新记录
    changeRouter(true)

}

const checkPermission = (path)=>{
    //用于判断角色权限
    const {user} = useUserStore()

    return user.role.rights.includes(path)
}

export default router;